package 稀疏数列和数组;

import java.net.SocketTimeoutException;

/**
 * @author: lin
 * @description:稀疏数列和数组的互相转化
 * 预期结果：
 * 原始的二维数组~~
 * 0	0	0	0	0	0	0	0	0	0	0
 * 0	0	1	0	0	0	0	0	0	0	0
 * 0	0	0	2	0	0	0	0	0	0	0
 * 0	0	0	0	0	0	0	0	0	0	0
 * 0	0	0	0	0	2	0	0	0	0	0
 * 0	0	0	0	0	0	0	0	0	0	0
 * 0	0	0	0	0	0	0	0	0	0	0
 * 0	0	0	0	0	0	0	0	0	0	0
 * 0	0	0	0	0	0	0	0	0	0	0
 * 0	0	0	0	0	0	0	0	0	0	0
 * 0	0	0	0	0	0	0	0	0	0	0
 *
 * 得到稀疏数组为~~~~
 * 11	11	3
 * 1	2	1
 * 2	3	2
 * 4	5	2
 *
 *
 * 恢复后的二维数组
 * 0	0	0	0	0	0	0	0	0	0	0
 * 0	0	1	0	0	0	0	0	0	0	0
 * 0	0	0	2	0	0	0	0	0	0	0
 * 0	0	0	0	0	0	0	0	0	0	0
 * 0	0	0	0	0	2	0	0	0	0	0
 * 0	0	0	0	0	0	0	0	0	0	0
 * 0	0	0	0	0	0	0	0	0	0	0
 * 0	0	0	0	0	0	0	0	0	0	0
 * 0	0	0	0	0	0	0	0	0	0	0
 * 0	0	0	0	0	0	0	0	0	0	0
 * 0	0	0	0	0	0	0	0	0	0	0
 * @time: 2021/8/4 15:32
 */
public class SpartArrays {
    public static void main(String[] args) {
        //1.1创建一个11*11的二维数组
        int a[][] = new int[11][11];
        //1.2往数组中存储数据
        a[1][2] = 1;
        a[2][3] = 2;
        a[4][5] = 2;
        //1.3输出该原始二维数组
        System.out.println("原始二维数组为：");
        for (int[] row : a) {
            for (int col : row) {
                System.out.printf("   " + col);
            }
            System.out.println();
        }
        //2.0 获取数据个数
        int sum = 0;
        for (int i = 0; i < 11; i++) {
            for (int j = 0; j < 11; j++) {
                if (a[i][j] != 0) sum++;
            }
        }
        System.out.println(sum);
        //2.1 新建一个稀疏数组
        int spartArrays[][] = new int[sum+1][3];
        //2.2 给首行赋值
        spartArrays[0][0] = 11;
        spartArrays[0][1] = 11;
        spartArrays[0][2] = sum;
        //2.3 给稀疏数组赋值
        int count = 0;
        for (int row = 0;row < 11;row ++) {
            for (int col = 0;col < 11;col++) {
                if (a[row][col]!=0){
                    count++;
                    spartArrays[count][0] = row;
                    spartArrays[count][1] = col;
                    spartArrays[count][2] = a[row][col];
                }
            }
        }
        //2.4 输出稀疏数组
        System.out.println("二维数组为");
        for (int row = 0; row <= count; row++) {
            for (int col = 0; col < 3; col++) {
                System.out.printf("  " + spartArrays[row][col]);
            }
            System.out.println();
        }
    //3.获取原始数组数据
        int b[][] = new int[spartArrays[0][0]][spartArrays[0][1]];
        for (int i = 1; i < spartArrays.length; i++) {
            b[spartArrays[i][0]][spartArrays[i][1]] = spartArrays[i][2];
        }
        //3.1输出数组
        System.out.println("稀疏数组转为二维数组:");
        for (int[] row : b) {
            for (int col : row) {
                System.out.printf("  "+ col);
            }
            System.out.println();
        }



    }
}
